package util

import (
	"time"
)

// const
const (
	OneSecond        = 1
	SecondsPerMinute = 60 * OneSecond
	SecondsPerHour   = 60 * SecondsPerMinute
	SecondsPerDay    = 24 * SecondsPerHour
	SecondsPerWeek   = 7 * SecondsPerDay
)

// GetStartOfDay GetStartOfDay
func GetStartOfDay(timestamp int64) int64 {
	return timestamp - timestamp%SecondsPerDay
}

// GetEndOfDay GetStartOfDay
func GetEndOfDay(timestamp int64) int64 {
	return GetStartOfDay(timestamp) + SecondsPerDay - 1
}

// GetRestSecondsOfDay 获取当前时间离当天结束的剩余秒数
func GetRestSecondsOfDay() int64 {
	endOfDay := GetEndOfDay(GetTimestamp() + GetDiffSeconds())
	return endOfDay - (GetTimestamp() + GetDiffSeconds())
}

// GetStartOfMonth 返回当前时间截 月的第一天
func GetStartOfMonth(timestamp int64) int64 {
	date := time.Unix(timestamp-GetDiffSeconds(), 0)
	year := date.Year()
	month := date.Month()

	startOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)

	return startOfMonth.Unix()
}

// GetEndOfMonth GetEndOfMonth
func GetEndOfMonth(timestamp int64) int64 {
	date := time.Unix(timestamp-GetDiffSeconds(), 0)
	year := date.Year()
	month := date.Month()

	numMonth := int(month)
	nextMonth := numMonth + 1
	if nextMonth > 12 {
		nextMonth = 1
		year++
	}

	startOfNextMonth := time.Date(year, time.Month(nextMonth), 1, 0, 0, 0, 0, time.UTC)

	return GetStartOfMonth(startOfNextMonth.Unix()) - 1
}

// GetRestSecondsOfMonth 获取当前时间离当月结束的剩余秒数
func GetRestSecondsOfMonth() int64 {
	endOfDay := GetEndOfMonth(GetTimestamp() + GetDiffSeconds())
	return endOfDay - (GetTimestamp() + GetDiffSeconds())
}

// GetStartOfWeek GetStartOfWeek
func GetStartOfWeek(timestamp int64) int64 {
	date := time.Unix(timestamp-GetDiffSeconds(), 0)
	week := date.Weekday()
	if week == 0 {
		week = 7
	}

	// 本周过去整天的秒数
	passSecondsDaysOfWeek := (week - 1) * SecondsPerDay

	return GetStartOfDay(timestamp - int64(passSecondsDaysOfWeek))
}

// GetEndOfWeek GetEndOfWeek
func GetEndOfWeek(timestamp int64) int64 {
	return GetStartOfWeek(timestamp) + 7*SecondsPerDay - 1
}

// GetRestSecondsOfWeek 获取当前时间离当周结束的剩余秒数
func GetRestSecondsOfWeek() int64 {
	endOfDay := GetEndOfWeek(GetTimestamp() + GetDiffSeconds())
	return endOfDay - (GetTimestamp() + GetDiffSeconds())
}
